package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.PageSortRoles;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantApply;
import com.wmh.baseservice.merchant.pojo.MerchantBankCard;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.pojo.MerchantPlotRent;
import com.wmh.baseservice.merchant.service.MerchantApplyService;
import com.wmh.baseservice.merchant.service.MerchantBankCardService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantPlotRentService;
import com.wmh.baseservice.user.pojo.UsRentOrder;
import com.wmh.baseservice.user.service.UsRentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author wmh generator
 * @since 2022-01-07
 */
@Api(tags = "商家银行卡表")
@RestController
@RequestMapping(value = "merchant/merchantBankCard", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
public class MerchantBankCardController {

    @Resource
    private MerchantBankCardService merchantBankCardService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantApplyService merchantApplyService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantPlotRentService merchantPlotRentService;
    @Resource
    private UsRentOrderService usRentOrderService;

    @ApiOperation("列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, Integer sort ,String remark, String cardNum, String bankName, String cardName, String createTimeScope) {
        Long id = (Long) request.getAttribute("id");
        // 设置分页排序规则
        PageUtil.setPageSortRoles(pageInfo,sort,"create_time");
        //执行分页辅助工具
        PageResult<MerchantBankCard> pageResult = new PageUtil<MerchantBankCard>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantBankCard.MERCHANT_ID, id);
            if(CommUtil.checkNull(remark)){
                queryWrapper.like(MerchantBankCard.REMARK,remark);
            }
            if(CommUtil.checkNull(cardNum)){
                queryWrapper.like(MerchantBankCard.CARD_NUM,cardNum);
            }
            if(CommUtil.checkNull(bankName)){
                queryWrapper.like(MerchantBankCard.BANK_NAME,bankName);
            }
            if(CommUtil.checkNull(cardName)){
                queryWrapper.like(MerchantBankCard.CARD_NAME,cardName);
            }
            if(CommUtil.checkNull(createTimeScope)){
                List<String> list = JSON.parseArray(createTimeScope, String.class);
                queryWrapper.between(MerchantBankCard.CREATE_TIME, list.get(0),list.get(1));
            }
            merchantBankCardService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("提现明细")
    @PostMapping("withdrawalDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String withdrawalDetail() {
        Long id = (Long) request.getAttribute("id");
        JSONObject object = new JSONObject(true);
        //总余额
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        object.put("totalBalance", merchantInfo.getBalance());
        //提现中
        BigDecimal applyIng = merchantApplyService.listForUpdate(new QueryWrapper<MerchantApply>().eq(MerchantApply.MERCHANT_ID, id).eq(MerchantApply.STATUS, 0)).
                stream().map(MerchantApply::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        object.put("applyIng", applyIng);
        //已提现
        BigDecimal successApply = merchantApplyService.listForUpdate(new QueryWrapper<MerchantApply>().eq(MerchantApply.MERCHANT_ID, id).eq(MerchantApply.STATUS, 1)).
                stream().map(MerchantApply::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        object.put("successApply", successApply);
        //个人收益占比
        object.put("shares",merchantInfo.getShares());
        //查出当前不可提现金额
        List<UsRentOrder> usRentOrders=usRentOrderService.queryMyRentOrder(id);
        final BigDecimal[] noWith = {BigDecimal.ZERO};
        usRentOrders.stream().map(item -> JSONObject.parseObject(item.getSnapshot())).map(snap -> snap.getBigDecimal("deposit")).forEach(deposit -> noWith[0] = noWith[0].add(deposit));
        object.put("noWith",noWith[0]);
        return ReturnBody.success(object);
    }

    @ApiOperation("添加或修改银行卡")
    @PostMapping("addOrUpdate")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String addOrUpdate(MerchantBankCard merchantBankCard) {
        Long id = (Long) request.getAttribute("id");
        MerchantBankCard card = merchantBankCardService.getOneForUpdate(
                new QueryWrapper<MerchantBankCard>()
                        .eq(MerchantBankCard.CARD_NUM, merchantBankCard.getCardNum()));
        if (CommUtil.checkNull(card)) {
            if (!CommUtil.checkNull(merchantBankCard.getId())) {
                return ReturnBody.error("卡号已存在");
            } else {
                if (!card.getId().equals(merchantBankCard.getId())) {
                    return ReturnBody.error("卡号已存在");
                }
            }
        }
        if (CommUtil.checkNull(merchantBankCard.getId())) {
            MerchantBankCard raw = merchantBankCardService.getByIdForUpdate(merchantBankCard.getId());
            if (!raw.getMerchantId().equals(id)) {
                return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
            }
            //有提现审核中的不可修改
            int count = merchantApplyService.count(new QueryWrapper<MerchantApply>().eq(MerchantApply.BANK_CARD_ID, merchantBankCard.getId()).eq(MerchantApply.STATUS, 0));
            if (count != 0) {
                return ReturnBody.error("该卡有提现申请正在审核中，为避免汇款错误，请等待审核结束后再操作");
            }
        }
        merchantBankCard.setMerchantId(id);
        if (!merchantBankCardService.saveOrUpdate(merchantBankCard)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("删除")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String delete(Long id) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantBankCard raw = merchantBankCardService.getByIdForUpdate(id);
        if (!raw.getMerchantId().equals(merchantId)) {
            return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
        }
        int count = merchantApplyService.count(new QueryWrapper<MerchantApply>().eq(MerchantApply.BANK_CARD_ID, id).eq(MerchantApply.STATUS, 0));
        if (count != 0) {
            return ReturnBody.error("该卡有提现申请正在审核中，为避免汇款错误，请等待审核结束后再操作");
        }
        if (!merchantBankCardService.removeById(id)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

}
